package com.shu.mmall.common;

import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.map.annotate.JsonSerialize;

import java.io.Serializable;

/**
 * JsonSerialize保证序列化json的时候，如果时null的对象，key也会消失
 * @author shujinhao
 */
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class Result<T> implements Serializable {

    private int status;
    private String msg;
    private T data;

    private Result(int status){
        this.status=status;
    }
    private Result(int status,T data){
        this.status=status;
        this.data=data;
    }
    private Result(int status,String msg,T data){
        this.status=status;
        this.msg=msg;
        this.data=data;
    }
    private Result(int status,String msg){
        this.status=status;
        this.msg=msg;
    }

    /**
     * 是否成功
     * JsonIgnore使之不在json序列化结果当中
     * @return 是否成功
     */
    @JsonIgnore
    public boolean isSuccess(){
        return this.status==ResponseCode.SUCCESS.getCode();
    }


    /**
     * 成功
     * @param <T> 泛型
     * @return 成功的结果
     */
    public static <T> Result<T> createBySuccess(){
        return new Result<>(ResponseCode.SUCCESS.getCode());
    }
    public static <T> Result<T> createBySuccessMessage(String msg){
        return new Result<>(ResponseCode.SUCCESS.getCode(),msg);
    }
    public static <T> Result<T> createBySuccess(T data){
        return new Result<>(ResponseCode.SUCCESS.getCode(),data);
    }
    public static <T> Result<T> createBySuccess(String msg,T data){
        return new Result<>(ResponseCode.SUCCESS.getCode(),msg,data);
    }

    /**
     * 失败
     * @param <T> 泛型
     * @return 失败的寄过
     */
    public static <T> Result<T> createByError(){
        return new Result<>(ResponseCode.ERROR.getCode(),ResponseCode.ERROR.getDesc());
    }
    public static <T> Result<T> createByErrorMessage(String errorMsg){
        return new Result<>(ResponseCode.ERROR.getCode(),errorMsg);
    }
    public static <T> Result<T> createByErrorCodeMessage(int errorCode,String errorMsg){
        return new Result<>(errorCode,errorMsg);
    }



    public int getStatus(){
        return this.status;
    }
    public T getData(){
        return this.data;
    }
    public String getMsg(){
        return this.msg;
    }
}
